package com.hitsz.application;


import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.hitsz.R;
import com.hitsz.base.Cat;
import com.hitsz.base.Feed;
import com.hitsz.global.Config;
import com.hitsz.global.UserInfor;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class ModeSelectActivity extends AppCompatActivity implements View.OnClickListener {

    Config conf = Config.getInstance();
    OkHttpClient okHttpClient = new OkHttpClient();
    String TAG = "Cat";
    public String res = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mode_select);

        // 插入假数据
//        this.mock();

        // 三个按钮使用功能
        findViewById(R.id.cat_details_button).setOnClickListener(this);
        findViewById(R.id.cat_haunt_button).setOnClickListener(this);
        findViewById(R.id.cat_feed_button).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        // 跳转到猫猫详细信息界面
        if(view.getId() == R.id.cat_details_button) {

            postSend1(conf.getUsername());
            // 睡2秒钟等待响应
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 记录当前用户id
            try {
                JSONObject jsonObject = new JSONObject(res);
                JSONArray  jsonArray = jsonObject.getJSONArray("body");
                ArrayList<Cat> cats = new ArrayList<Cat>();
                for(int i=0; i<=jsonArray.length()-1; ++i){
                    JSONObject jo = jsonArray.getJSONObject(i);
                    String cat_id = jo.getString("cat_id");
                    String cat_name = jo.getString("cat_name");
                    String color_name = jo.getString("color_name");
                    String haunt_name = jo.getString("haunt_name");
                    String nature_name = jo.getString("nature_name");
                    String breed_name = jo.getString("breed_name");
                    cats.add(new Cat(cat_id, cat_name, color_name, haunt_name, nature_name, breed_name));
                }
                conf.setCats(cats);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            conf.setType("cat");
            Intent intent = new Intent(ModeSelectActivity.this, DetailsActivity.class);
            startActivity(intent);
            this.finish();
        }
        // 跳转到猫猫登记打卡界面
        else if(view.getId() == R.id.cat_haunt_button) {
            Intent intent = new Intent(ModeSelectActivity.this, ClockInActivity.class);
            startActivity(intent);
            this.finish();
        }

        // 跳转到猫猫投喂登记界面
        else if(view.getId() == R.id.cat_feed_button) {
            postSend2(conf.getUsername());

            // 睡2秒钟等待响应
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 记录当前用户id
            try {
                JSONObject jsonObject = new JSONObject(res);
                JSONArray  jsonArray = jsonObject.getJSONArray("body");
                ArrayList<Feed> feeds = new ArrayList<Feed>();
                for(int i=0; i<=jsonArray.length()-1; ++i){
                    JSONObject jo = jsonArray.getJSONObject(i);
                    String feed_id = jo.getString("feed_id");
                    String name = jo.getString("name");
                    String cat_name = jo.getString("cat_name");
                    String feed_time = jo.getString("feed_time");
                    feed_time = convertTime2GMT08(feed_time).substring(0,19);
                    String feed_food = jo.getString("feed_food");
                    feeds.add(new Feed(feed_id, name, cat_name, feed_time, feed_food));
                }
                conf.setFeeds(feeds);
            } catch (JSONException | ParseException e) {
                e.printStackTrace();
            }

            conf.setType("feed");
            Intent intent = new Intent(ModeSelectActivity.this, DetailsActivity.class);
            startActivity(intent);
            this.finish();
        }
    }

    // 返回后只能回到主界面
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            Intent intent = new Intent(ModeSelectActivity.this, MainActivity.class);
            startActivity(intent);
            this.finish();
        }
        return true;
    }

    // 插入假数据测试
    public void mock() {
        ArrayList<Cat> cats = new ArrayList<Cat>();
        cats.add(new Cat("1","花花", "yellow", "T1教学楼", "聪明", "缅因"));
        cats.add(new Cat("1","花花", "yellow", "T1教学楼", "聪明", "缅因"));
        cats.add(new Cat("1","花花", "yellow", "T1教学楼", "聪明", "缅因"));
        cats.add(new Cat("1","花花", "yellow", "T1教学楼", "聪明", "缅因"));
        cats.add(new Cat("1","花花", "yellow", "T1教学楼", "聪明", "缅因"));
        conf.setCats(cats);

        ArrayList<Feed> feeds = new ArrayList<Feed>();
        feeds.add(new Feed("20", "黄晓明", "红红", "2022-12-13T10:08", "猪肉"));
        feeds.add(new Feed("20", "黄晓明", "红红", "2022-12-13T10:08", "猪肉"));
        feeds.add(new Feed("20", "黄晓明", "红红", "2022-12-13T10:08", "猪肉"));
        feeds.add(new Feed("20", "黄晓明", "红红", "2022-12-13T10:08", "猪肉"));
        feeds.add(new Feed("20", "黄晓明", "红红", "2022-12-13T10:08", "猪肉"));
        feeds.add(new Feed("20", "黄晓明", "红红", "2022-12-13T10:08", "猪肉"));
        conf.setFeeds(feeds);
    }

    // 获取数据
    public void getData(){

    }

    // get cats
    public void postSend1(String username){
        new Thread(){
            @Override
            public void run(){
                FormBody formBody = new FormBody.Builder()
                        .add("username",username).build();
                Request request = new Request.Builder()
                        .url("http://192.168.56.1:3007/api/getCatDetails")
                        .post(formBody).build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    res = response.body().string();
                    Log.i(TAG,"body:"+res);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    // get feeds
    public void postSend2(String username){
        new Thread(){
            @Override
            public void run(){
                FormBody formBody = new FormBody.Builder()
                        .add("username",username).build();
                Request request = new Request.Builder()
                        .url("http://192.168.56.1:3007/api/getFeedDetails")
                        .post(formBody).build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    res = response.body().string();
                    Log.i(TAG,"body:"+res);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public static String convertTime2GMT08(String time) throws ParseException {
        //时间格式自己定义
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:sszzz");
        TimeZone tz;

        // 设置时区为"GMT+08:00"（需要输出时间的时区 ）
        tz = TimeZone.getTimeZone("GMT+08:00");

        // 后面的+0000为国际时间，其它时区请自行更换 （如GMT+08:00 为+0800）
        Date date = df.parse(time.replace("T", " ").replace(".000Z", "") + "+0000");

        // 获取默认的DateFormat，用于格式化Date
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置时区为tz
        sdf.setTimeZone(tz);
        // 获取格式化后的字符串
        String str = sdf.format(date);
        return str;
    }

}